package com.apes.scm.pur.purchaseOrder.service;

import com.apes.framework.callback.InputInter;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.repository.PurchaseOrderRepository;
import com.apestech.framework.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

@Service("purchaseAnalysisService")
public class PurchaseAnalysisService {

    @Autowired
    private EntityManager entityManager;

    public void savePurchaseAnalysis() {
        // 判断当前月份是否是当月第一天
        LocalDate localDate = LocalDate.now();
        LocalDate firstDay = localDate.with(TemporalAdjusters.firstDayOfMonth());

        // 为当月第一天统计上月数据到历史数据表中
        if (firstDay.getDayOfMonth() == localDate.getDayOfMonth()) {
            Date preData = DateUtil.parse(localDate.plusMonths(-1).toString(), DateUtil.SHOW_MONTH_FORMAT);
            String yearAndDay = DateUtil.format(preData, DateUtil.SHOW_MONTH_FORMAT);

            Query query = entityManager.createNativeQuery(this.insertSql(yearAndDay));
            query.executeUpdate();
        }
    }

    private String insertSql(String date) {
        return "" +
                "INSERT INTO PUR_PURCHASE_ANALYSIS\n" +
                "  (DATE_APPROVE, SUPPLIER_ID, STORE_ID, STORE_NAME, CLASSIFY_ID,\n" +
                "   CLASSIFY_NAME, CATEGORY_ID, CATEGORY_NAME, PROVINCE_ID, CITY_ID,\n" +
                "   CITY_NAME, DUMP_PRICE)\n" +
                "  SELECT DATE_APPROVE, SUPPLIER_ID, STORE_ID, STORE_NAME, CLASSIFY_ID,\n" +
                "         CLASSIFY_NAME, CATEGORY_ID, CATEGORY_NAME, PROVINCE_ID, CITY_ID,\n" +
                "         CITY_NAME, DUMP_PRICE\n" +
                "    FROM V_PURCHASE_ANALYSIS_SUM\n" +
                "   WHERE DATE_APPROVE = '"+ date +"' ";

    }

}
